package cn.ljh.zard.executor;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义线程工厂
 * 需要重写new Thread方法
 * 1、包含了线程的前缀名字
 * 2、因为创建线程，需要用到一个线程组 需要在初始化这个对象的线程中获取对应的线程组信息
 */
public class ZardThreadFactory implements ThreadFactory {

    // 线程组
    private ThreadGroup threadGroup;

    private AtomicInteger threadCountIncrement = new AtomicInteger(1);
    // 线程的前缀
    private static String threadPrefix = "pool-zard";



    public ZardThreadFactory() {
        this.threadGroup = Thread.currentThread().getThreadGroup();

        threadPrefix = threadPrefix
                + threadCountIncrement.incrementAndGet()
                + "-thread-sign";


    }

    @Override
    public Thread newThread(Runnable r) {

        Thread t = new Thread(threadGroup, r, threadPrefix + threadCountIncrement.incrementAndGet(), 0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;

    }
}
